import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_user.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import '../../../../bean/bean_integral.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
enum RankType {
  times,
  tianfu,
}

///代码清单
class MineMyRahkIntegralItemLevelPage extends StatefulWidget {
  final String configId;
  final StreamController<String> dateSelectStream;

  MineMyRahkIntegralItemLevelPage(
      {@required this.configId, Key key, this.dateSelectStream})
      : super(key: key);

  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<MineMyRahkIntegralItemLevelPage> {
  bool _isLoading = true;
  bool _isLoading2 = false;

  @override
  void initState() {
    super.initState();
    getMyScoreDataFunction();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return LoadingWidget();
    }
    if (_integralList.length == 0) {
      return NoDataWidget(
        clickCallBack: () async {
          setState(() {
            _isLoading = true;
          });
          await getMyScoreDataFunction();
          ToastUtils.showToast("已刷新");
        },
      );
    }

    return RefreshIndicator(
      notificationPredicate: (ScrollNotification notifation) {
        //该属性包含当前ViewPort及滚动位置等信息
        ScrollMetrics scrollMetrics = notifation.metrics;
        if (scrollMetrics.minScrollExtent == 0) {
          return true;
        } else {
          return false;
        }
      },
      onRefresh: () async {
        setState(() {
          _isLoading2 = true;
        });
        await getMyScoreDataFunction();
        ToastUtils.showToast("已刷新");
        return true;
      },
      child: NestedScrollView(
        body: buildAnimatedSwitcher(context),
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverToBoxAdapter(
              child: buildAvgScoreWidget(),
            ),
          ];
        },
      ),
    );
  }

  ///AnimatedSwitcher 的基本使用
  AnimatedSwitcher buildAnimatedSwitcher(BuildContext context) {
    return AnimatedSwitcher(
      ///动画执行切换时间
      duration: const Duration(milliseconds: 200),

      ///动画构建器 构建指定动画类型
      transitionBuilder: (Widget child, Animation<double> animation) {
        //执行缩放动画
        return FadeTransition(child: child, opacity: animation);
      },

      ///执行动画的子 Widget
      ///只有子 Widget 被切换时才会触发动画
      child: _isLoading2
          ? LoadingWidget()
          : ListView.builder(
        key: ValueKey("$_count"),
              itemCount: _integralList.length,
              itemBuilder: (BuildContext context, int index) {
                IntegralStatBean item = _integralList[index];
                return Container(
                  child: buildItemRankContainer(item, index),
                );
              },
            ),
    );
  }

  Container buildItemRankContainer(IntegralStatBean item, int index) {
    return Container(
      height: 66,
      margin: EdgeInsets.only(top: 10, left: 12, right: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              SizedBox(
                width: 12,
              ),
              Container(
                child: buildItemIndex(index),
                width: 40,
                alignment: Alignment.center,
              ),
              SizedBox(
                width: 12,
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      "${item.userRealName}",
                      style: TextStyle(
                        color: Colors.blueGrey,
                        fontSize: 16,
                      ),
                    ),
                    SizedBox(
                      height: 4,
                    ),
                    Text(
                      "${item.userDepartment}",
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 14,
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(
                width: 12,
              ),
              Container(
                width: 80,
                alignment: Alignment.centerRight,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      item == null ? "无" : "${item.examineCountValid}次",
                      style: TextStyle(
                        color: Colors.red,
                        fontSize: 16,
                      ),
                    ),
                    SizedBox(
                      height: 4,
                    ),
                    Text(
                      item == null ? "无" : "${item.examineScore}分",
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 14,
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(
                width: 12,
              ),
            ],
          ),
          Container(
            height: 1.0,
            color: Colors.grey[200],
            margin: EdgeInsets.only(top: 8),
          ),
        ],
      ),
    );
  }

  Widget buildItemIndex(int index) {
    return index < 3
        ? Image.asset(
            "assets/images/2.0x/icon_rank_${index + 1}.png",
            width: 26,
          )
        : Text(
            "${index + 1}",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
          );
  }

  int _count = 0;
  RankType _rankType = RankType.times;

  //平均分
  Widget buildAvgScoreWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          margin: EdgeInsets.only(top: 16, bottom: 16),
          height: 200,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Container(
                  alignment: Alignment.center,
                  child: Image.asset(
                    buildRankImagePath(),
                    height: 200,
                  ),
                ),
              ),
              Positioned(
                top: 166,
                child: Text(
                  buildRankText(),
                  style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.w600,
                      fontSize: 16),
                ),
              ),
              Positioned(
                top: 0,
                left: 22,
                child: Container(
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      InkWell(
                        onTap: () {
                          _count++;
                          _rankType = RankType.times;
                          setState(() {
                            _isLoading2 = true;
                          });
                          getMyScoreDataFunction();
                        },
                        child: Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(
                              left: 8, right: 8, top: 4, bottom: 4),
                          child: Text(
                            "积分排行",
                            style: TextStyle(
                              color: _rankType == RankType.times
                                  ? Colors.white
                                  : Colors.red,
                            ),
                          ),
                          decoration: BoxDecoration(
                            color: _rankType == RankType.times
                                ? Colors.red
                                : Colors.white,
                            border: Border.all(color: Colors.red),
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(20),
                              bottomLeft: Radius.circular(20),
                            ),
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          _count++;
                          _rankType = RankType.tianfu;
                          setState(() {
                            _isLoading2 = true;
                          });
                          getMyScoreDataFunction();
                        },
                        child: Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(
                              left: 8, right: 8, top: 4, bottom: 4),
                          child: Text(
                            "参与频率排名",
                            style: TextStyle(
                              color: _rankType == RankType.times
                                  ? Colors.red
                                  : Colors.white,
                            ),
                          ),
                          decoration: BoxDecoration(
                            color: _rankType == RankType.tianfu
                                ? Colors.red
                                : Colors.white,
                            border: Border.all(color: Colors.red),
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(20),
                              bottomRight: Radius.circular(20),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        buildUserRankContainer()
      ],
    );
  }

  Container buildUserRankContainer() {
    UserBean userBean = UserHelper.getInstance.userBean;
    return Container(
      height: 80,
      margin: EdgeInsets.only(top: 10, left: 12, right: 12),
      child: Stack(
        children: [
          Positioned.fill(
            child: Image.asset(
              "assets/images/2.0x/bg_ranking_list_own.png",
              fit: BoxFit.fill,
            ),
          ),
          Positioned.fill(
            child: Row(
              children: [
                SizedBox(
                  width: 12,
                ),
                Icon(
                  Icons.scanner_outlined,
                  color: Colors.white,
                ),
                SizedBox(
                  width: 12,
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        "${userBean.reamName}",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      Text(
                        "${userBean.department} - ${userBean.userPost}",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(
                  width: 12,
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      _userIntegralStatBean == null
                          ? "无"
                          : "${_userIntegralStatBean.examineCountValid}次",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                      ),
                    ),
                    SizedBox(
                      height: 4,
                    ),
                    Text(
                      _userIntegralStatBean == null
                          ? "无"
                          : "${_userIntegralStatBean.examineScore}分",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                      ),
                    )
                  ],
                ),
                SizedBox(
                  width: 12,
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  String buildRankText() {
    if (_userIntegralStatBean == null) {
      return "暂无排名";
    } else {
      String str = "第${_userIntegralStatBean.rankNumber}名";
      return str;
    }
  }

  String buildRankImagePath() {
    if (_userIntegralStatBean == null) {
      return "assets/images/2.0x/rank4.png";
    } else {
      String str =
          "assets/images/2.0x/rank${_userIntegralStatBean.rankNumber}.png";
      if (_userIntegralStatBean.rankNumber > 4) {
        str = "assets/images/2.0x/rank4.png";
      }
      return str;
    }
  }

  CancelToken _cancelToken;
  List<IntegralStatBean> _integralList = [];
  IntegralStatBean _userIntegralStatBean;

  Future<bool> getMyScoreDataFunction() async {
    if (_isLoading2) {
      await Future.delayed(Duration(milliseconds: 400));
    }
    Map<String, dynamic> monthMap = {
      "configId": widget.configId,
      "sort": _rankType == RankType.times ? "TIMES" : "AVERAGE",
    };
    if (_cancelToken != null && !_cancelToken.isCancelled) {
      _cancelToken.cancel();
    }
    _cancelToken = new CancelToken();
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.integralStatisticsRecoder,
      queryParameters: monthMap,
      cancelTag: _cancelToken,
    );

    if (statisRresponseInfo.success) {
      var responseData = statisRresponseInfo.data;
      if (responseData != null) {
        List list = responseData['list'];
        List<IntegralStatBean> newList = [];
        for (int i = 0; i < list.length; i++) {
          IntegralStatBean _rankStatBean = IntegralStatBean.fromJson(list[i]);
          newList.add(_rankStatBean);
        }
        _integralList = newList;

        if (responseData['userIntegral'] != null) {
          _userIntegralStatBean =
              IntegralStatBean.fromJson(responseData['userIntegral']);
        } else {
          _userIntegralStatBean = null;
        }
      }
    }
    _isLoading2 = false;
    _isLoading = false;

    if (mounted) {
      setState(() {});
    }

    return Future.value(true);
  }
}
